import re

from rest_framework import serializers
from django_redis import get_redis_connection
from users.models import User
from django.contrib.auth.models import Group


class UserGroupsSerializer(serializers.ModelSerializer):
    """
    用户组序列化类
    """
    class Meta:
        model = Group
        fields = "__all__"


class CreateUserSerializer(serializers.ModelSerializer):
    """创建用户的序列化器"""
    password2 = serializers.CharField(label='确认密码', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    allow = serializers.CharField(label='同意协议', write_only=True)

    class Meta:
        model = User
        fields = ('id', 'password', 'password2', 'sms_code', 'mobile', 'allow')
        extra_kwargs = {
            'password': {
                'write_only': True,
                'min_length': 6,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许6-20个字符的密码',
                    'max_length': '仅允许6-20个字符的密码',
                }
            }
        }

    def validate_mobile(self, value):
        if not re.match(r'^1[3456789]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def validate_allow(self, value):
        if value != 'true':
            raise serializers.ValidationError('请同意用户协议')

    def validate(self, attrs):
        if attrs['password'] != attrs['password2']:
            raise serializers.ValidationError('两次输入的密码不一致')
        redis_connection = get_redis_connection('verify_codes')
        real_sms_code = redis_connection.get('sms_code_{}'.format(attrs['mobile'])).decode()
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码无效')
        if real_sms_code != attrs['sms_code']:
            raise serializers.ValidationError('短信验证码错误')
        return attrs

    def create(self, validated_data):
        del validated_data['password2']
        del validated_data['sms_code']
        del validated_data['allow']
        user = User.objects.create(**validated_data)
        user.set_password(validated_data['password'])
        user.save()
        return user


